uniform sampler2DRect tex;

#define s2(a, b)        temp = a; a = min(a, b); b = max(temp, b);
#define mn3(a, b, c)    s2(a, b); s2(a, c);
#define mx3(a, b, c)    s2(b, c); s2(a, c);

#define mnmx3(a, b, c)      mx3(a, b, c); s2(a, b);
#define mnmx4(a, b, c, d)   s2(a, b); s2(c, d); s2(a, c); s2(b, d);
#define mnmx5(a, b, c, d, e)    s2(a, b); s2(c, d); mn3(a, c, e); mx3(b, d, e);
#define mnmx6(a, b, c, d, e, f) s2(a, d); s2(b, e); s2(c, f); mn3(a, b, c); mx3(d, e, f);



void main(void){
    mat3 I;
    vec3 sample;
    vec2 uv = gl_TexCoord[0].st;
    float color = 0.0;
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            I[i][j] = texture2DRect(tex, ivec2(uv) + ivec2(i-1, j-1)).r;
        }
    }
    
    color = I[0][0]/9.0 + I[0][1]/9.0 + I[0][2]/9.0 + I[1][0]/9.0 + I[1][1]/9.0; + I[1][2]/9.0 + I[2][0]/9.0 + I[2][1]/9.0 + I[2][2]/9.0;

    float temp;
    
    temp = min(I[0][0], I[0][1]);
    temp = min(temp, I[0][2]);
    temp = min(temp, I[1][0]);
    temp = min(temp, I[1][1]);
    temp = min(temp, I[1][2]);
    temp = min(temp, I[2][0]);
    temp = min(temp, I[2][1]);
    temp = min(temp, I[2][2]);
    
    if(temp < 0.5) temp = 0.5;
    
        
    /*mnmx6(I[0][0], I[0][1], I[0][2], I[1][0], I[1][1], I[1][2]);
    mnmx5(I[0][1], I[0][2], I[1][0], I[1][1], I[2][0]);
    mnmx4(I[0][2], I[1][0], I[1][1], I[2][1]);
    mnmx3(I[1][0], I[1][1], I[2][2]);*/

    gl_FragColor = vec4(vec3(temp), 1.0);   
}
